package com.kinsin.kinsinutil

import android.content.Context
import java.io.*

/**
 * 文件工具类
 * @author kinsin
 *
 * // 在Application中初始化（推荐） <p>
 * class MyApp : Application() {
 *     override fun onCreate() {
 *         super.onCreate()
 *         FileUtil.getInstance(this)
 *     }
 * }
 * <p>
 * // 使用示例
 * val fileUtil = FileUtil.getInstance(context)
 * <p>
 * // 存储字符串
 * fileUtil.saveStringToFile("config.txt", "Hello World")
 * <p>
 * // 读取字符串
 * val content = fileUtil.readStringFromFile("config.txt")
 * <p>
 * // 重命名文件
 * fileUtil.renameFile("config.txt", "settings.txt")
 * <p>
 * // 删除文件
 * fileUtil.deleteFile("settings.txt")
 * <p>
 * // 创建目录
 * val success = fileUtil.createDirectory("documents") <p>
 * if (success) { <p>
 *     // 在子目录保存文件 <p>
 *     fileUtil.saveStringToFile("documents/note.txt", "重要笔记") <p>
 * }
 * <p>
 * // 检查目录是否存在
 * if (fileUtil.directoryExists("downloads")) {
 *     // 操作已存在的目录
 * }
 * <p>
 * // 删除目录及其内容
 * fileUtil.deleteDirectory("temp_cache")
 */
class FileUtilWithOutPermission private constructor(context: Context) {
    
    companion object {
        @Volatile
        private var INSTANCE: FileUtilWithOutPermission? = null

        fun getInstance(context: Context): FileUtilWithOutPermission {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: FileUtilWithOutPermission(context.applicationContext).also { INSTANCE = it }
            }
        }
    }

    private val appContext = context.applicationContext
    private val internalStorageDir: File by lazy { appContext.filesDir }

    // 存储字符串到文件
    fun saveStringToFile(fileName: String, content: String): Boolean {
        return try {
            File(internalStorageDir, fileName).also {
                it.parentFile?.mkdirs()
                FileWriter(it).use { writer -> writer.write(content) }
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    // 从文件读取字符串
    fun readStringFromFile(fileName: String): String? {
        return try {
            BufferedReader(FileReader(File(internalStorageDir, fileName))).use { it.readText() }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    // 存储字节数组到文件
    fun saveBytesToFile(fileName: String, data: ByteArray): Boolean {
        return try {
            FileOutputStream(File(internalStorageDir, fileName)).use { it.write(data) }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    // 从文件读取字节数组
    fun readBytesFromFile(fileName: String): ByteArray? {
        return try {
            FileInputStream(File(internalStorageDir, fileName)).use { it.readBytes() }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    // 删除文件
    fun deleteFile(fileName: String): Boolean {
        return File(internalStorageDir, fileName).let { file ->
            file.exists() && file.delete()
        }
    }

    // 文件重命名
    fun renameFile(oldName: String, newName: String): Boolean {
        return File(internalStorageDir, oldName).let { oldFile ->
            val newFile = File(internalStorageDir, newName)
            if (oldFile.exists() && !newFile.exists()) {
                oldFile.renameTo(newFile)
            } else {
                false
            }
        }
    }

    // 获取文件绝对路径（调试用）
    fun getFilePath(fileName: String): String {
        return File(internalStorageDir, fileName).absolutePath
    }

    // 新增目录操作方法
    fun createDirectory(directoryName: String): Boolean {
        return try {
            File(internalStorageDir, directoryName).let { dir ->
                // 如果目录不存在则创建（支持多级目录）
                if (!dir.exists()) dir.mkdirs() else true
            }
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    // 检查目录是否存在
    fun directoryExists(directoryName: String): Boolean {
        return File(internalStorageDir, directoryName).let {
            it.exists() && it.isDirectory
        }
    }

    // 删除目录（递归删除）
    fun deleteDirectory(directoryName: String): Boolean {
        return File(internalStorageDir, directoryName).let { dir ->
            if (dir.isDirectory) {
                dir.deleteRecursively()
            } else {
                false
            }
        }
    }
}